package org.jeecg.modules.ledgerBaseInfo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.backups.entity.Backups;
import org.jeecg.modules.backups.service.IBackupsService;
import org.jeecg.modules.ledgerBaseInfo.entity.LedgerBaseInfo;
import org.jeecg.modules.ledgerBaseInfo.service.ILedgerBaseInfoService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 进出厂运输车辆台账(基本信息表)
 * @Author: jeecg-boot
 * @Date:   2025-09-30
 * @Version: V1.0
 */
@Api(tags="进出厂运输车辆台账(基本信息表)")
@RestController
@RequestMapping("/ledgerBaseInfo/ledgerBaseInfo")
@Slf4j
public class LedgerBaseInfoController extends JeecgController<LedgerBaseInfo, ILedgerBaseInfoService> {
	@Autowired
	private ILedgerBaseInfoService ledgerBaseInfoService;
	@Autowired
	private IBackupsService backupsService;
	
	/**
	 * 分页列表查询
	 *
	 * @param ledgerBaseInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-分页列表查询")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-分页列表查询", notes="进出厂运输车辆台账(基本信息表)-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(LedgerBaseInfo ledgerBaseInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<LedgerBaseInfo> queryWrapper = QueryGenerator.initQueryWrapper(ledgerBaseInfo, req.getParameterMap());
		Page<LedgerBaseInfo> page = new Page<LedgerBaseInfo>(pageNo, pageSize);
		IPage<LedgerBaseInfo> pageList = ledgerBaseInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param ledgerBaseInfo
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-添加")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-添加", notes="进出厂运输车辆台账(基本信息表)-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody LedgerBaseInfo ledgerBaseInfo) {
		ledgerBaseInfoService.save(ledgerBaseInfo);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param ledgerBaseInfo
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-编辑")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-编辑", notes="进出厂运输车辆台账(基本信息表)-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody LedgerBaseInfo ledgerBaseInfo) {
		ledgerBaseInfoService.updateById(ledgerBaseInfo);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-通过id删除")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-通过id删除", notes="进出厂运输车辆台账(基本信息表)-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		ledgerBaseInfoService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-批量删除")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-批量删除", notes="进出厂运输车辆台账(基本信息表)-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.ledgerBaseInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出厂运输车辆台账(基本信息表)-通过id查询")
	@ApiOperation(value="进出厂运输车辆台账(基本信息表)-通过id查询", notes="进出厂运输车辆台账(基本信息表)-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoService.getById(id);
		if(ledgerBaseInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ledgerBaseInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ledgerBaseInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LedgerBaseInfo ledgerBaseInfo) {
        return super.exportXls(request, ledgerBaseInfo, LedgerBaseInfo.class, "进出厂运输车辆台账(基本信息表)");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LedgerBaseInfo.class);
    }

	@AutoLog(value = "导出-进出厂运输车辆台账(基本信息表)")
	@ApiOperation(value="导出-进出厂运输车辆台账(基本信息表)", notes="导出-进出厂运输车辆台账(基本信息表)")
	@PostMapping(value = "/m/getBaseInfo")
	public Result<?> getBaseInfo(@RequestParam(name="pageNo") Integer pageNo,
								 @RequestParam(name="pageSize") Integer pageSize) {
		LambdaQueryWrapper<LedgerBaseInfo> wrapper = Wrappers.lambdaQuery();
		wrapper.orderByDesc(LedgerBaseInfo::getCreateTime);
		Page<LedgerBaseInfo> page = new Page<LedgerBaseInfo>(pageNo, pageSize);
		IPage<LedgerBaseInfo> pageList = ledgerBaseInfoService.page(page, wrapper);
		List<LedgerBaseInfo> records = pageList.getRecords();
		String filename = pageNo + "_" + pageSize + "_" + "进出厂运输车辆台账(基本信息表).xls";
		try {
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
					"进出厂运输车辆台账(基本信息表)", "进出厂运输车辆台账(基本信息表)"), LedgerBaseInfo.class, records);
			File savefile = new File("C:\\backups\\ygc");
			if (!savefile.exists()) {
				boolean mkDirs = savefile.mkdirs();
				if (!mkDirs){
					throw new RuntimeException("创建文件夹失败");
				}
			}
			FileOutputStream fos = new FileOutputStream("C:\\backups\\ygc\\" + filename);
			workbook.write(fos);
			fos.close();

			// 获取文件大小并转换为KB
			Path filePath = Paths.get("C:\\backups\\ygc", filename);
			long fileSizeBytes = Files.size(filePath);
			int fileSizeKB = (int) (fileSizeBytes / 1024);

			Backups byFileName = backupsService.getByFileName(filename);
			if (byFileName != null) {
				byFileName.setBackupsTime(new Date()).setFileName(filename).setFileUrl(filename).setFileSize(fileSizeKB).setStatus(1);
				backupsService.updateById(byFileName);
			} else {
				Backups backups = new Backups();
				backups.setBackupsTime(new Date()).setFileName(filename).setFileUrl(filename).setFileSize(fileSizeKB).setStatus(1);
				backupsService.save(backups);
			}

			log.info("---------------备份执行结束----------------");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Result.OK("备份成功！");
	}

}
